﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GymTimer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GymTimer.PageModels
{
    public partial class ScheduleDetailPageModel : ObservableObject, IQueryAttributable
    {

        private Schedule _schedule=new Schedule();

        //private readonly ScheduleRepository _scheduleRepository;
        //private readonly ExerciseRepository _exerciseRepository;
        private readonly TimerDataBase _timerDataBase;

        private readonly ModalErrorHandler _modalErrorHandler;

        [ObservableProperty]
        private string _name  = string.Empty;

        [ObservableProperty]
        private int _ID = 0;

        [ObservableProperty]
        private int _prepareTime= 0;


        [ObservableProperty]
        private List<Exercise> _exercises = [];


        public ScheduleDetailPageModel(TimerDataBase timerDatabase, ModalErrorHandler modalErrorHandler)
        {
            _timerDataBase = timerDatabase;
            _modalErrorHandler = modalErrorHandler;

        }

        public void ApplyQueryAttributes(IDictionary<string, object> query)
        {
            if (query.ContainsKey("id"))
            {
                int id= Convert.ToInt32(query["id"]);
                LoadData(id).FireAndForgetSafeAsync(_modalErrorHandler);
            }
            else
            {
                _schedule=new Schedule();
            }
        }

        private async Task LoadData(int id)
        {

            _schedule= await _timerDataBase.GetScheduleAsync(id);
            Name = _schedule.Name;
            ID = id;
            Exercises=await _timerDataBase.GetExerciseAsync(id);


            Console.WriteLine("id");
        }

        [RelayCommand]
        private async Task Save()
        {

            _schedule.Name = Name;
            _schedule.RepareTime = PrepareTime;


            await _timerDataBase.SaveSchedule(_schedule);

            await Shell.Current.GoToAsync("..");
            await AppShell.DisplayToastAsync("Project saved");
        }

        [RelayCommand]
        private async Task AddExercise(int  scheduleId)
        {
            await Shell.Current.GoToAsync($"exercise?sheculdeId={scheduleId}");
        }

        [RelayCommand]
        private async Task NavigateToExercise(Exercise exercise)
        {
            await Shell.Current.GoToAsync($"exercise?id={exercise.ID}");
        }

    }
}
